package com.itheima.service.serviceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.dto.ClazzDto;
import com.itheima.domain.pojo.Clazz;
import com.itheima.domain.vo.ClazzVo;
import com.itheima.domain.vo.PageResult;
import com.itheima.mapper.ClazzMapper;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-08-19 11:01
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Override
    public PageResult getClazzList(ClazzDto clazzDto) {
        PageHelper.startPage(clazzDto.getPage(), clazzDto.getPageSize());
        Page<ClazzVo> P = clazzMapper.getClazzList(clazzDto);
        return new PageResult<>(P.getTotal(), P.getResult());
    }

    @Override
    public void deleteClazz(Integer id) {
        clazzMapper.deleteClazz(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addClazz(Clazz clazz) {
        LocalDateTime now = LocalDateTime.now();
        // 班级名称判重
        countName(clazz);
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazzMapper.addClazz(clazz);
    }

    @Override
    public Clazz getClazzId(Integer id) {
        Clazz clazz = clazzMapper.getClazzId(id);
        return clazz;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClazz(Clazz clazz) {
        // 数据回显
        Clazz oldClazz = getClazzId(clazz.getId());
        LocalDateTime now = LocalDateTime.now();
        // 班级名称判重
        if (!Objects.equals(oldClazz.getName(), clazz.getName())){
            countName(clazz);
        }
        clazz.setUpdateTime(now);
        clazzMapper.updateClazz(clazz);
    }

    @Override
    public List<Clazz> selectClazzList(Clazz clazz) {
        List<Clazz> clazzList = clazzMapper.selectClazzList(clazz);
        return clazzList;
    }

    /** 班级名判重 */
    private void countName(Clazz clazz) {
        Integer nameCount = clazzMapper.getClazzNameCount(clazz.getName());
        if (nameCount > 0) {
            throw new RuntimeException("班级名称已存在");
        }
    }

}
